/*
 * @ProjectName: 编程学习
 * @Copyright:   2021 HangZhou Yiyuery Dev, Ltd. All Right Reserved.
 * @address:     微信搜索公众号「架构探险之道」获取更多资源。
 * @date:        2021/1/13 10:23 下午
 * @blog:         https://yiyuery.blog.csdn.net/
 * @description: 本内容仅限于编程技术学习使用，转发请注明出处.
 */
package pub.dsb.example.nio;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * <p>
 *
 * </p>
 *
 * @author Yi
 * @date 2021/1/13 10:23 下午
 * @sine 1.0
 */
public class ZeroCopyTest {

    public static void main(String[] args) throws IOException {
        long t1 = System.currentTimeMillis();
        // 获取文件输入通道 和 输出通道
        FileChannel inChannel = FileChannel.open(Paths.get("/Users/xiazhaoyang/Documents/Books/计算机/网络通信/TCP-IP详解卷1：协议.pdf"),
                StandardOpenOption.READ);
        FileChannel outChannel = FileChannel.open(Paths.get("/Users/xiazhaoyang/Ashe/workspace/architectrue-adventure/netty-examples/netty-chapter-1/out/production/COPY2.pdf"),
                StandardOpenOption.WRITE,StandardOpenOption.READ,StandardOpenOption.CREATE);
        // 输入通道和输出通道之间的内存映射文件（内存映射文件存在于堆外内存中）
        MappedByteBuffer inMappedBuffer = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size());
        MappedByteBuffer outMappedBuffer = outChannel.map(FileChannel.MapMode.READ_WRITE, 0, inChannel.size());
        // 直接对内存映射文件进行读写
        byte[] source = new byte[inMappedBuffer.limit()];
        inMappedBuffer.get(source);
        outMappedBuffer.put(source);
        inChannel.close();
        outChannel.close();
        System.out.println("复制耗时：" + (System.currentTimeMillis() - t1));
        File file = new File("/Users/xiazhaoyang/Ashe/workspace/architectrue-adventure/netty-examples/netty-chapter-1/out/production/COPY2.pdf");
        System.out.println("文件大小:"+file.length());
    }
}
